package com.lambkit.config;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ClassUtil;
import com.jfinal.config.Interceptors;
import com.lambkit.JFinalApp;
import com.lambkit.JFinalAppConfig;
import com.lambkit.core.Lambkit;
import com.lambkit.core.LambkitApp;
import com.lambkit.core.annotion.App;
import com.lambkit.core.annotion.Config;
import com.lambkit.core.annotion.ScanPackage;
import com.lambkit.core.service.ScanClassProcess;
import com.lambkit.JFLambkit;
import com.lambkit.module.JFModule;
import com.lambkit.module.JFModules;
import com.lambkit.util.Printer;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author yangyong(孤竹行)
 */
public class DefaultJFinalConfig extends BaseJFinalConfig {
    @Override
    public void configModule(JFModules modules) {
        Class<?> targetClass = Lambkit.context().getTargetClass();
        //搜索LambkitApp的之类
        List<String> packages = null;
        ScanPackage scanPackage = targetClass.getAnnotation(ScanPackage.class);
        if(scanPackage != null) {
            String[] pkgs = scanPackage.value();
            if(pkgs!=null && pkgs.length > 0) {
                packages = CollUtil.newArrayList(pkgs);
            }
        }
        if(packages == null) {
            packages = CollUtil.newArrayList(ClassUtil.getPackage(targetClass));
        }
        for (String packageName : packages) {
            JFLambkit.getApp().classOperateService().scanPackageBySuper(packageName, JFModule.class, new ScanClassProcess() {
                @Override
                public void process(Class<?> clazz) {
                    JFModule jfModule = (JFModule) Lambkit.get(clazz);
                    Printer.print(this, "starter", "module：" + clazz.getName());
                    modules.addModule(jfModule);
                }
            });
        }
    }

    @Override
    public void configInterceptor(Interceptors interceptors) {
        super.configInterceptor(interceptors);
    }

    @Override
    public void onStart() {
        super.onStart();
        System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date()) + " - Lambkit服务启动完成！");
    }

    @Override
    public void onStop() {
        super.onStop();
        System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date()) + " - Lambkit服务即将停止！");
    }
}
